package com.loyin.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import com.et.mvc.JsonView;
import com.et.mvc.View;
import com.igs.parse.quartz.DowLoadHtml;
import com.igs.parse.query.QueryCountUtil;
import com.loyin.model.DownloadUrl;
import com.loyin.model.DownloadUrlVo;
import com.loyin.model.UserInfo;
import com.loyin.model.UserInfoVo;
import com.loyin.util.MD5;
import com.loyin.util.Page;

public class DownloadUrlController extends ApplicationController
{
	private Logger log = Logger.getLogger(this.getClass());

	public void list()
	{
		auth();
		UserInfoVo userinfovo = (UserInfoVo) session.getAttribute("user_session");
		StringBuffer sql = null;
		if(userinfovo.getRoleclass()==1)
			sql = new StringBuffer(" and userid = ? ");
		else
			sql = new StringBuffer();
		DownloadUrl msginfo = new DownloadUrl();
		try
		{
			String pagenostr = request.getParameter("pageNo");
			String pagesizestr = request.getParameter("pageSize");
			if (pagenostr == null || "".equals(pagenostr.trim()))
			{
				pagenostr = "1";
			}
			if (pagesizestr == null || "".equals(pagesizestr.trim()))
			{
				pagesizestr = this.pagesize + "";
			}
			Page page = new Page(0, Integer.parseInt(pagenostr), Integer.parseInt(pagesizestr), null);
			List<Object> paramlist = new ArrayList<Object>();
			paramlist.add(userinfovo.id);
			String websiteid = request.getParameter("websiteid");
			request.setAttribute("websiteid", websiteid);
			if (websiteid != null && !"".equals(websiteid.trim()))
			{
				sql.append(" and websiteid = ? ");
				paramlist.add(websiteid.trim());
			}

			String title = request.getParameter("title");
			request.setAttribute("title", title);
			if (title != null && !"".equals(title.trim()))
			{
				sql.append(" and title like ? ");
				paramlist.add("%" + title.trim() + "%");
			}
			List<DownloadUrl> list = (List<DownloadUrl>) msginfo.findAll(DownloadUrl.class, " 1=1 "+sql.toString(), paramlist.toArray(), null, page.getPageSize(), page.start);
			List<DownloadUrlVo> listVo=new ArrayList<DownloadUrlVo>();
			for(DownloadUrl du: list)
			{
				DownloadUrlVo duv=new DownloadUrlVo();
				duv.setId(du.getId());
				duv.setTitle(du.getTitle());
				duv.setUrl(du.getUrl());
				duv.setRecordtime(du.getRecordtime());
				duv.setIsdownload(du.getIsdownload());
				listVo.add(duv);
			}
			long count = msginfo.count(msginfo.getClass(), null, paramlist.toArray());
			page = new Page(count, Integer.parseInt(pagenostr), Integer.parseInt(pagesizestr), listVo);
			request.setAttribute("page", page);
			//加载下载大小
			double folderSize=QueryCountUtil.getDownLoadSizeCount(String.valueOf(userinfovo.getId()));
			request.setAttribute("folderSize", folderSize);
		} catch (Exception e)
		{
			log.error("查看下载文件异常", e);
			request.setAttribute("stat", "E");
			request.setAttribute("msg", "访问出错");
		}
	}

	public View delete()
	{
		auth();
		Map<String, Object> map = new HashMap<String, Object>();
		try
		{
			String[] ids = request.getParameterValues("ids");
			StringBuffer sql = new StringBuffer("id in (");
			if (ids != null && ids.length > 0)
			{
				for (String id : ids)
				{
					sql.append(id);
					sql.append(",");
				}
			}
			sql.append("EE)");

			int res = DownloadUrl.deleteAll(DownloadUrl.class, sql.toString().replaceAll(",EE", "").replaceAll("EE", ""), null);
			if (res > 0)
			{
				map.put("stat", "S");
				map.put("msg", "删除成功");
			} else
			{
				map.put("stat", "F");
				map.put("msg", "删除失败");
			}
		} catch (Exception e)
		{
			log.error("删除异常", e);
			map.put("stat", "E");
			map.put("msg", "删除异常");
		}
		return new JsonView(map);
	}
	
	/** 下载本网站 */
	public void download(long id)
	{
		auth();
		if (id != 0)
		{
			DownloadUrl downloadUrl = new DownloadUrl();
			try
			{
				downloadUrl=downloadUrl.find(DownloadUrl.class, id);
				//先判断是否已经下载了
				if(DowLoadHtml.isDownload(id))
				{
					//打包并下载
					String filenamedownload=DowLoadHtml.zipHtmlFile(id);
					request.setAttribute("filenamedownload", filenamedownload);
					request.setAttribute("filenamedisplay", downloadUrl.getTitle()+".zip");
				}
				downloadUrl.setIsdownload(1);
				downloadUrl.save();
			} catch (Exception e)
			{
				log.error("下载网站异常", e);
			}
		}
	}
	
	/** 删除下载网页，清空空间 */
	public void deleteHtml(long id)
	{
		auth();
		if (id != 0)
		{
			DownloadUrl downloadUrl = new DownloadUrl();
			try
			{
				downloadUrl=downloadUrl.find(DownloadUrl.class, id);
				//先判断是否已经下载了
				if(DowLoadHtml.isDownload(id))
				{
					//打包并下载
					DowLoadHtml.deleteDownLoadHtml(id);
					downloadUrl.setIsdownload(-1);
					downloadUrl.setDownloadsize(0);
					downloadUrl.save();
				}
				redirect("/downloadurl/list" );
			} catch (Exception e)
			{
				log.error("删除下载网站异常", e);
			}
		}
	}
	
	public void duanxinmao()
	{
		auth();
		try
		{
			Map<String, Object> map = new HashMap<String, Object>();
			String usercode=request.getParameter("usercode");
			String pwd=request.getParameter("pwd");
			UserInfo user = new UserInfo();
			List<UserInfo> userlist = (List<UserInfo>) user.findBySql(user.getClass(),
					"select * from igs_userinfo where (usercode=? or email=? or phone=?) and pwd=? ", new Object[]
					{ usercode, usercode, usercode, MD5.getMD5ofStr(pwd) });
			if (userlist == null || userlist.isEmpty() == true)
			{
				request.setAttribute("stat", "F");
				request.setAttribute("msg", "用户名或密码错误！");
			} else
			{
				SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd");
				String strDate=df.format(new Date());
				UserInfo userinfo = userlist.get(0);
				/**
				 * SELECT * FROM igs_downloadurl dlu
left join igs_userinfo ui on dlu.userid=ui.id
				 */
				int i=0;
				String querySql=" SELECT * FROM igs_downloadurl "
								+" where userid="+userinfo.getId()+" "
								+" and SUBSTRING(recordtime,1,10)='"+strDate+"' "
								;
				DownloadUrl msginfo=new DownloadUrl();
				List<DownloadUrl> list = (List<DownloadUrl>) msginfo.findBySql(DownloadUrl.class, querySql);
				if(list!=null && list.size()>0)
				{
					request.setAttribute("dataLength", list.size());
					request.setAttribute("dataList", list);
				}
				else
				{
					request.setAttribute("dataLength", 0);
					request.setAttribute("dataList", null);
				}
				request.setAttribute("stat", "S");
			}
			
		} catch (Exception e)
		{
			log.error("", e);
			request.setAttribute("stat", "F");
			request.setAttribute("msg_error", "访问出错，请联系系统管理员！");
		}
	}
	
	
}
